package com.mt.restaurant.service.material.impl;

import com.mt.restaurant.dao.material.MaterialDao;

import com.mt.common.core.exception.BusinessException;
import com.mt.common.core.web.base.PageDTO;
import com.mt.common.core.web.base.PageResultDTO;
import com.mt.common.core.web.base.BaseEntity;
import com.mt.common.core.web.BaseService;
import com.mt.restaurant.dao.material.StoreMaterialDao;
import com.mt.restaurant.service.material.SupplyMaterialService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.mt.restaurant.entity.material.Material;
import com.mt.restaurant.service.material.MaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.security.spec.ECField;
import java.util.concurrent.TimeUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@Transactional
public class MaterialServiceBean extends BaseService implements MaterialService {

    private static Logger logger = LogManager.getLogger();

	@Autowired
	private MaterialDao materialDao;

	@Resource
	private RedisTemplate<String, List<Material>> redisTemplate;

	@Autowired
	StringRedisTemplate stringRedisTemplate;

	@Autowired
	SupplyMaterialService supplyMaterialService;

	@Autowired
	private StoreMaterialDao storeMaterialDao;

	/**
	 * 根据分页参数查询材料集合
	 *
	 * @param pageDTO 分页条件
	 */
	@Override
	public PageResultDTO findMaterials(PageDTO pageDTO){
		if (pageDTO.getCurrentPage() != null) {
			pageDTO.setStartIndex((pageDTO.getCurrentPage() - 1) * pageDTO.getPageSize());
		}
		//TODO:请在此校验参数的合法性
		this.validateFindMaterials(pageDTO);
		List<Material> materialDTOS = this.materialDao.findMaterials(pageDTO);
		Long totalCount = this.materialDao.findMaterialTotalCount(pageDTO);

		PageResultDTO pageResultDTO = new PageResultDTO();
		pageResultDTO.setTotalCount(totalCount);
		pageResultDTO.setDatas(materialDTOS);

		return pageResultDTO;
	}

	/**
	 * 查询全部材料集合
	 *
	 */
	@Override
	public List<Material> findAllMaterials(){
		return this.materialDao.findAllMaterials();
	}

	/**
	 * 查询所有材料集合(只提取ID 和 Name)
	 *
	 */
	@Override
	public List<Material> findAllMaterialsWithIdName(){
		//TODO:请在此校验参数的合法性
		this.validateFindAllMaterialsWithIdName();
		return this.materialDao.findAllMaterialsWithIdName();
	}

	/**
	 * 根据名称查询材料集合(只提取ID 和 Name)
	 *
	 * @param materialName 名称
	 */
	@Override
	public List<Material> findMaterialsWithIdNameByName(String materialName){
		//TODO:请在此校验参数的合法性
		this.validateFindMaterialsWithIdNameByName(materialName);
		//TODO:缓存取对应参数
		Set<String> keys = stringRedisTemplate.keys("searchData:Material_where_materialName_" + materialName);
		List<Material> materials = new ArrayList<>();
		if (keys.isEmpty()) {
		materials = this.materialDao.findMaterialsWithIdNameByName(materialName);
		redisTemplate.opsForValue().set("searchData:Material_where_materialName_" + materialName, materials, 30, TimeUnit.DAYS);
		} else {
		materials = redisTemplate.opsForValue().get("searchData:Material_where_materialName_" + materialName);
		}
		return materials;
	}

	/**
	 * 根据ID查询指定的材料(只提取ID 和 Name)
	 *
	 * @param materialId Id
	 */
	@Override
	public Material findMaterialsWithIdNameById(Long materialId){
		//TODO:请在此校验参数的合法性
		this.validateFindMaterialsWithIdNameById(materialId);
		return this.materialDao.findMaterialsWithIdNameById(materialId);
	}

	/**
	 * 根据ID查询指定的材料
	 *
	 * @param materialId Id
	 */
	@Override
	public Material findMaterial(Long materialId){
		//TODO:请在此校验参数的合法性
		this.validateFindMaterial(materialId);
		return this.materialDao.findMaterial(materialId);
	}

	/**
	 * 根据ID查询指定的材料(包含外键)
	 *
	 * @param materialId Id
	 */
	@Override
	public Material findMaterialWithForeignName(Long materialId){
		//TODO:请在此校验参数的合法性
		this.validateFindMaterialWithForeignName(materialId);
		return this.materialDao.findMaterialWithForeignName(materialId);
	}

	/**
	 * 新增材料
	 *
	 * @param material 实体对象
	 */
	@Override
	public Material saveMaterial(Material material){
		//TODO:请在此校验参数的合法性
		this.validateSaveMaterial(material);
		//TODO:填充公共参数
		this.setSavePulicColumns(material);
		Long rows = this.materialDao.saveMaterial(material);
		if(rows != 1)
		{
			String error = "新增保存材料出错，数据库应该返回1,但返回了 "+rows;
			throw new BusinessException(error);
		}
		rows = storeMaterialDao.updateStoreMaterialMaxPriceById(material.getEid(),material.getMaxPrice());
		if(rows != 1)
		{
			String error = "修改保存材料价格出错，数据库应该返回1,但返回了 "+rows+",数据可能被删除";
			throw new BusinessException(error);
		}
		return material;
	}

	/**
	 * 更新材料
	 *
	 * @param material 实体对象
	 */
	@Override
	public Material updateMaterial(Material material){
		//TODO:请在此校验参数的合法性
		this.validateUpdateMaterial(material);
		Long rows = this.materialDao.updateMaterial(material);
		if(rows != 1)
		{
			String error = "修改保存材料出错，数据库应该返回1,但返回了 "+rows+",数据可能被删除";
			throw new BusinessException(error);
		}
		/*rows = storeMaterialDao.updateStoreMaterialMaxPriceById(material.getEid(),material.getMaxPrice());
		if(rows != 1)
		{
			String error = "修改保存材料价格出错，数据库应该返回1,但返回了 "+rows+",数据可能被删除";
			throw new BusinessException(error);
		}*/
		return material;
	}

	/**
	 * 根据ID删除材料
	 *
	 * @param materialId ID
	 */
	@Override
	public void deleteMaterial(Long materialId){
		//TODO:请在此校验参数的合法性
		this.validateDeleteMaterial(materialId);

		Map<Class<? extends BaseEntity>,EntityUsage> entityUsageMap = this.checkForeignEntity(Material.class, materialId);
		if(entityUsageMap != null && entityUsageMap.size() >0){
			StringBuilder errors = new StringBuilder();
			errors.append("计划删除的数据正在被以下数引用\n");
			for(EntityUsage entityUsage : entityUsageMap.values()){
				errors.append("\t").append(entityUsage.getEntityLabel()).append("\n");
				for(Map.Entry<Long,String> entry : entityUsage.getUsageIdNames().entrySet() ){
					errors.append("\t\t").append(entry.getKey()).append("\t").append(entry.getValue()).append("\n");
				}
			}
			errors.append("，不能删除，请检查处理后再删除");
			throw  new BusinessException(errors.toString());
		}

		Long rows = this.materialDao.deleteMaterial(materialId);
		if(rows != 1){
			String error = "删除材料出错，数据可能已经被删除";
			throw new BusinessException(error);
		}
	}

	//TODO:---------------验证-------------------

	private void validateFindMaterials(PageDTO pageDTO) {
	//TODO:请使用下面方法添加数据过滤条件
	//		pageDTO.addFilter("creatorId",this.getLoginUserId());
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateMaterial()写法
	}

	private void validateFindMaterialsWithIdNameByName(String materialName) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateMaterial()写法
	}


	private void validateFindAllMaterialsWithIdName() {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateMaterial()写法
	}

	private void validateFindMaterialsWithIdNameById(Long materialId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateMaterial()写法
	}

	private void validateFindMaterial(Long materialId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateMaterial()写法
	}

	private void validateFindMaterialWithForeignName(Long materialId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateMaterial()写法
	}

	private void validateSaveMaterial(Material material) {
	//不为空判断
	if (material.getEid() != null || material.getCreatorId() != null || material.getCreateDatetime() != null) {
	throw new BusinessException("非法请求");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateMaterial()写法
	}

	private void validateUpdateMaterial(Material material) {
	//不为空判断
	if (material.getEid() == null) {
	throw new BusinessException("唯一标识不能为空");
	}
	//是否存在判断
	if (this.materialDao.findMaterialTotalCount(PageDTO.create(Material.FIELD_ID, material.getEid())) == 0) {
	throw new BusinessException("修改的材料 " + material.getName() + " 不存在，修改失败，请重试或联系管理员");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateMaterial()写法
	}

	private void validateDeleteMaterial(Long materialId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateMaterial()写法
	}

	@Override
	public boolean canDownloadAttachment(String formName, Long id) {
	return true;
	}
}
